<?php
// 获取自动分配哈希算法


class DuanUrlHash
{
    private $seq = array(
        'a', '0', 's', '9', 'd', 'f', 'g',
        '1', 'h', 'j', '8', 'k', 'l', '2',
        '7', 'q', 'w', '3', 'e', 'r', 't',
        '6', 'y', 'u', 'i', '4', 'o', 'p',
        'z', 'x', 'c', '5', 'v', 'b', 'n',
        '-', 'm'
        );
    private $seq_last_char = 'm';
    private $seq_zero_char = 'a';

    private $seq_next = array(
        'a' => '0',
        '0' => 's',
        's' => '9',
        '9' => 'd',
        'd' => 'f',
        'f' => 'g',
        'g' => '1',
        '1' => 'h',
        'h' => 'j',
        'j' => '8',
        '8' => 'k',
        'k' => 'l',
        'l' => '2',
        '2' => '7',
        '7' => 'q',
        'q' => 'w',
        'w' => '3',
        '3' => 'e',
        'e' => 'r',
        'r' => 't',
        't' => '6',
        '6' => 'y',
        'y' => 'u',
        'u' => 'i',
        'i' => '4',
        '4' => 'o',
        'o' => 'p',
        'p' => 'z',
        'z' => 'x',
        'x' => 'c',
        'c' => '5',
        '5' => 'v',
        'v' => 'b',
        'b' => 'n',
        'n' => '-',
        '-' => 'm',
        'm' => 'a'
        );

    /// 模拟一个37位的整数，获取下一个有效整数的方式
    function getNextHash($prehash, $len=4)
    {    
        // 如果没有初始值
        if (empty($prehash))
        {
            $token = '';
            for($i=0; $i<$len;$i++) $token.= $this->seq_zero_char;
            return $token;
        }
        else
        {
            // 有初始值
            $prehash_len = strlen ( $prehash );
            $token = '';
            $inc = true;
            for( $i=0; $i< $prehash_len; $i++)
            {
                $pos = $prehash_len - $i - 1;
                $char = substr($prehash , $pos, 1);
                if ($inc == true)
                {
                    $char = $this->seq_next[$char];
                    if ($char == $this->seq_zero_char)
                    {
                        $inc = true;
                    }
                    else
                    {
                        $inc = false;
                    }
                } 
                $token= $char . $token;
            }
            return $token;
        }
    }
};

//$url = new DuanUrlHash();
//var_dump ($url->getNextHash('ammm'));
//var_dump ($url->getNextHash('timeis'));
//var_dump ($url->getNextHash(null));
